package com.moi.topslidinglogindemo;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements View.OnClickListener,TextWatcher {

    private EditText name;
    private EditText pw;
    private String text;
    private String password;
    private TextView mation;
    private TextView login;
    private ImageView go;
    private Button mButton;
    private LinearLayout linearLayout;
    private TopSlidingLayout topSlidingLayout;
    private CheckBox rememberPassword;
    private SharedPreferences sp;
    private TextView version;

    private PackageInfo pi = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        //轻量级数据库，用来记住密码
        sp = this.getSharedPreferences("userInfo", Context.MODE_APPEND);
        rememberPassword = (CheckBox) findViewById(R.id.cb_password);
        //下滑登陆菜单
        topSlidingLayout = (TopSlidingLayout) findViewById(R.id.top_sliding_layout);
        //除了下滑，再加上一个按钮跳转
        go = (ImageView) findViewById(R.id.iv_go);
        name = (EditText) findViewById(R.id.et_name);
        pw = (EditText) findViewById(R.id.et_pass_word);
        //密码默认弹出数字输入法
        pw.setInputType(InputType.TYPE_CLASS_NUMBER);
        //隐藏密码
        pw.setTransformationMethod(PasswordTransformationMethod.getInstance());
        mation = (TextView) findViewById(R.id.tv_mation);

        login = (TextView) findViewById(R.id.tv_go);
        go.setOnClickListener(this);
        name.addTextChangedListener(this);
        pw.addTextChangedListener(this);
        login.setOnClickListener(this);

        //得到版本信息
        PackageManager pm = getApplicationContext().getPackageManager();//context为当前Activity上下文
        try {
            pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        version = (TextView) findViewById(R.id.tv_version);
        version.setText("ver."+pi.versionName);

        //这些是为了获取到下滑的滑动事件才实例化的
        mButton = (Button) findViewById(R.id.bt_content);
        linearLayout = (LinearLayout) findViewById(R.id.ll_content);

        //判断记住密码多选框的状态
        if (sp.getBoolean("ISCHECK", false)) {
            //设置默认是记录密码状态
            rememberPassword.setChecked(true);
            name.setText(sp.getString("USER_NAME", ""));
            pw.setText(sp.getString("PASSWORD", ""));
            if(sp.getBoolean("ISCHECK",true)) {
                //让记住密码，再次登陆时变色……
                login.setBackgroundResource(R.drawable.bt_orange);
                mation.setText("");
            }
        }

        /*name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                if (hasFocus) {//如果有焦点就显示软件盘

                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);

                } else {//否则就隐藏
                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });
        pw.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                if (hasFocus) {//如果有焦点就显示软件盘

                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);

                } else {//否则就隐藏
                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });*/

        //监听记住密码多选框按钮事件
        rememberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (rememberPassword.isChecked()) {
                    sp.edit().putBoolean("ISCHECK", true).apply();
                } else {
                    sp.edit().putBoolean("ISCHECK", false).apply();
                }
            }
        });

        //给这些显示在主页面上的控件添加滑动事件
        topSlidingLayout.setScrollEvent(go);
        topSlidingLayout.setScrollEvent(linearLayout);
        topSlidingLayout.setScrollEvent(mButton);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //Go跳转的点击事件
            case R.id.iv_go:
                if (topSlidingLayout.isTopLayoutVisible()) {
                    topSlidingLayout.scrollToContentFromTopMenu();
                } else {
                    topSlidingLayout.initShowTopState();
                    topSlidingLayout.scrollToTopMenu();

                    //让其跳转后焦点转移到editText，并弹出输入框
                    if (name.getText().toString().equals("")) {
                        name.requestFocus();
//                        InputMethodManager imm = (InputMethodManager) pw.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                    } else if (pw.getText().toString().equals("")) {
                        pw.requestFocus();
//                        InputMethodManager imm = (InputMethodManager) pw.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                    }
                }
                break;
            //登陆按钮的点击事件
            case R.id.tv_go:
                text = name.getText().toString();
                password = pw.getText().toString();
                //用户名和密码不为空时才能跳转
                if (!text.equals("") && !password.equals("")) {
                    //登录成功和记住密码框为选中状态才保存用户信息
                    if (rememberPassword.isChecked()) {
                        //记住用户名、密码、
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("USER_NAME", text);
                        editor.putString("PASSWORD", password);
                        editor.apply();
                    }
                    SecondActivity.actionStart(MainActivity.this, text);
                } else if (text.equals("")) {
                    Toast.makeText(MainActivity.this, R.string.enter_name, Toast.LENGTH_SHORT).show();
                } else if (password.equals("")) {
                    Toast.makeText(MainActivity.this, R.string.enter_pw, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        //两个框框都有内容时改变颜色&提示输出帐号密码
        if (!name.getText().toString().equals("") && !pw.getText().toString().equals("")) {
            login.setBackgroundResource(R.drawable.bt_orange);
            mation.setText("");
        } else if (!name.getText().toString().equals((""))) {
            login.setBackgroundResource(R.drawable.bt_blue);
            mation.setText(R.string.enter_pw);
        } else {
            login.setBackgroundResource(R.drawable.bt_blue);
            mation.setText(R.string.enter_name);
        }
    }

    @Override
    protected void onStop() {
        //如果记住密码没被选中，跳转完后清空密码
        if(!rememberPassword.isChecked()) {
            pw.setText("");
        }
        super.onPause();
    }

}
